package cc.rengu.redp.system.service.impl;

import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpConstant;
import cc.rengu.redp.common.utils.SortUtil;
import cc.rengu.redp.system.dao.UserMessageMapper;
import cc.rengu.redp.system.domain.UserMessage;
import cc.rengu.redp.system.service.UserMessageService;
import cc.rengu.redp.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author System
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserMessageServiceImpl extends ServiceImpl<UserMessageMapper, UserMessage> implements UserMessageService {

    @Autowired
    private UserService userService;

    @Override
    public IPage<UserMessage> findAllMessage(String[] range, String sourceType, Long userId, QueryRequest queryRequest) {
        Page<UserMessage> page = new Page<>();
        SortUtil.handlePageSort(queryRequest, page, "createTime", RedpConstant.ORDER_DESC, true);
        LambdaQueryWrapper<UserMessage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserMessage::getUserId, userId).orderByDesc(UserMessage::getCreateTime);
        if (range != null && range.length == 2 && StringUtils.isNotBlank(range[0]) && StringUtils.isNotBlank(range[1])) {
            lqw.between(UserMessage::getCreateTime, range[0], range[1]);
        }
        if (StringUtils.isNotBlank(sourceType) && "1|2".contains(sourceType)) {
            lqw.eq(UserMessage::getSourceType, sourceType);
        }

        return this.baseMapper.selectPage(page, lqw);
    }

    @Override
    public Integer getUnreadMessageCount(Long userId) {
        LambdaQueryWrapper<UserMessage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserMessage::getUserId, userId).eq(UserMessage::getReadFlg, false);
        return this.baseMapper.selectCount(lqw);
    }

    @Override
    public void read(Long id) {
        LambdaUpdateWrapper<UserMessage> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(UserMessage::getId, id).set(UserMessage::getReadFlg, true);
        this.update(lqw);
    }
}
